<template>
  <el-dialog :title="!dataForm.id ? 'Add User' : 'Edit User'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" autocomplete="off" label-width="140px">
      <el-form-item label="User Name" prop="username">
        <el-input v-model="dataForm.username" autocomplete="off" placeholder="Username"></el-input>
      </el-form-item>
      <el-form-item label="Password" prop="password" :class="{ 'is-required': !dataForm.id }">
        <el-input v-model="dataForm.password" type="password" auto-complete="new-password" placeholder="Password"></el-input>
      </el-form-item>
      <el-form-item label="Repeat Password" prop="comfirmPassword" :class="{ 'is-required': !dataForm.id }">
        <el-input v-model="dataForm.comfirmPassword" type="password" placeholder="Repeat password"></el-input>
      </el-form-item>
      <el-form-item label="Email" prop="email">
        <el-input v-model="dataForm.email" placeholder="Email"></el-input>
      </el-form-item>
      <el-form-item label="Phone" prop="phone">
        <el-input v-model="dataForm.phone" placeholder="Phone"></el-input>
      </el-form-item>
      <el-form-item label="Role" size="mini" prop="roleIdList">
        <el-checkbox-group :disabled="dataForm.id && (dataForm.id === '1' || dataForm.id === 1)" v-model="dataForm.roleIdList">
          <el-checkbox v-for="role in roleList" :key="role.id" :label="role.id">{{ role.alias }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="Status" size="mini" prop="enabled">
        <el-radio-group :disabled="dataForm.id && (dataForm.id === '1' || dataForm.id === 1)" v-model="dataForm.enabled">
          <el-radio :label="false">Disable</el-radio>
          <el-radio :label="true">Enable</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="Remark" size="mini" prop="remark">
        <el-input
          v-model="dataForm.remark"
          type="textarea"
          :rows="5"
          :autosize="{ minRows: 4 }"
          maxlength="200"
          show-word-limit
          resize="none"
          placeholder="Remark"
        ></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">Cancel</el-button>
      <el-button type="primary" @click="dataFormSubmit()">OK</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { isEmail, isMobile } from "@/utils/validate";
export default {
  data() {
    var validatePassword = (rule, value, callback) => {
      if (!this.dataForm.id && !/\S/.test(value)) {
        callback(new Error("Please provide your password"));
      } else {
        callback();
      }
    };
    var validateComfirmPassword = (rule, value, callback) => {
      if (!this.dataForm.id && !/\S/.test(value)) {
        callback(new Error("Please confirm your password"));
      } else if (this.dataForm.password !== value) {
        callback(new Error("Passwords do not match"));
      } else {
        callback();
      }
    };
    var validateEmail = (rule, value, callback) => {
      if (!isEmail(value)) {
        callback(new Error("Please provide a valid email address"));
      } else {
        callback();
      }
    };
    return {
      visible: false,
      roleList: [],
      dataForm: {
        id: 0,
        username: "",
        password: "",
        comfirmPassword: "",
        email: "",
        phone: "",
        roleIdList: [],
        enabled: true,
        remark: "",
      },
      dataRule: {
        username: [{ required: true, message: "Name is required", trigger: "blur" }],
        password: [{ validator: validatePassword, trigger: "blur" }],
        email: [{ validator: validateEmail, trigger: "blur" }],
        comfirmPassword: [{ validator: validateComfirmPassword, trigger: "blur" }],
      },
    };
  },

  methods: {
    async init(id) {
      this.dataForm.id = id || 0;
      const { code, data } = await this.$http.get("/sysRole/getList");
      this.roleList = code === 200 ? data : [];
      this.visible = true;
      await this.$nextTick();
      this.$refs["dataForm"].resetFields();
      if (this.dataForm.id) {
        const { code, data } = await this.$http.get(`/sysUser/${this.dataForm.id}/detail`);
        if (code === 200) {
          this.dataForm.username = data.username;
          this.dataForm.password = "";
          this.dataForm.email = data.email;
          this.dataForm.phone = data.phone;
          this.dataForm.roleIdList = data.roleList.map(i => i.id);
          this.dataForm.enabled = data.enabled;
          this.dataForm.remark = data.remark;
        }
      }
    },
    // 表单提交
    async formSubmitRequest(dataForm) {
      const payload = {
        username: dataForm.username,
        password: dataForm.password || undefined,
        email: dataForm.email,
        phone: dataForm.phone,
        enabled: dataForm.enabled,
        remark: dataForm.remark,
        roleIdList: dataForm.roleIdList,
      };
      if (dataForm.id) {
        return await this.$http.post(`/sysUser/${dataForm.id}/update`, payload);
      } else {
        return await this.$http.post(`/sysUser/create`, payload);
      }
    },
    dataFormSubmit() {
      this.$refs["dataForm"].validate(async valid => {
        if (valid) {
          const { code, msg } = await this.formSubmitRequest(this.dataForm);
          if (code === 200) {
            this.$message({
              message: "success",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.visible = false;
                this.$emit("refreshDataList");
              },
            });
          } else {
            this.$message.error(msg);
          }
        }
      });
    },
  },
};
</script>
